import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: 'http://localhost:8088',
  timeout: 5000 // 设置请求超时时间为5秒
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从localStorage中获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    // 判断响应状态
    if (res.code !== 200) {
      Message({
        message: res.message || '错误',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === 401) {
        router.push('/login')
      }
      return Promise.reject(new Error(res.message || '错误'))
    }
    return res
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default request 